package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Collections;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    private final String CART_PREFIX = "gulimall:cart:";

    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public CartItem addToCart(Long skuId, Integer number) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String res = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(res)) {
            //购物车无此商品
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                //1、远程查询当前要添加的商品信息
                R info = productFeignService.info(skuId);
                SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItem.setSkuId(skuId);
                cartItem.setCheck(true);
                cartItem.setCount(number);
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setTitle(skuInfo.getSkuTitle());
                cartItem.setPrice(skuInfo.getPrice());
            }, threadPoolExecutor);

            CompletableFuture<Void> getSkuAttrTask = CompletableFuture.runAsync(() -> {
                //2、远程查询sku的组合信息
                List<String> skuSaleAttrVales = productFeignService.getSkuSaleAttrVales(skuId);
                cartItem.setSkuAttr(skuSaleAttrVales);
            }, threadPoolExecutor);

            CompletableFuture.allOf(getSkuInfoTask, getSkuAttrTask).get();

            //3、商品添加到购物车
            //默认使用jdk的流，此处转JSON存储
            String cartItemJson = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), cartItemJson);

            return cartItem;
        } else {
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount() + number);

            //默认使用jdk的流，此处转JSON存储
            String cartItemJson = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), cartItemJson);

            return cartItem;
        }
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        return JSON.parseObject(res, CartItem.class);
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

        Cart cart = new Cart();

        List<CartItem> cartItems;

        if (userInfoTo.getUserId() != null) {
            //登录
            //获取登录后的购物车【没有合并】
            cartItems = getCartItems(userInfoTo.getUserId());
            //如果临时购物车的数据还没有进行合并
            List<CartItem> tempCartItems = getCartItems(userInfoTo.getUserKey());
            if (!tempCartItems.isEmpty()) {
                for (CartItem tempCartItem : tempCartItems) {
                    this.addToCart(tempCartItem.getSkuId(), tempCartItem.getCount());
                    //清空临时购物车
                    this.clearCart(userInfoTo.getUserKey());
                }
                //获取合并后的购物车
                cartItems = getCartItems(userInfoTo.getUserId());
            }
        } else {
            cartItems = getCartItems(userInfoTo.getUserKey());
        }

        cart.setItems(cartItems);

        return cart;
    }

    /**
     * 清空购物车
     *
     * @param cartKey
     */
    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(CART_PREFIX + cartKey);
    }

    @Override
    public void changeItemCheck(Long skuId, Integer check) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1);
        String json = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), json);
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);

        String json = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), json);
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getCurrentUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null) {
            return null;
        }
        List<CartItem> cartItems = this.getCartItems(userInfoTo.getUserId());
        return cartItems.stream().filter(CartItem::getCheck).map(item -> {
            //查询当前最新的价格
            BigDecimal price = productFeignService.getPrice(item.getSkuId());
            item.setPrice(price);
            return item;
        }).collect(Collectors.toList());
    }

    /**
     * 根据购物车key查询购物车列表
     *
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItems(Object cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(CART_PREFIX + cartKey);
        List<Object> values = hashOps.values();
        if (values != null && !values.isEmpty()) {
            return values.stream()
                    .map(obj -> JSON.parseObject((String) obj, CartItem.class))
                    .collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    /**
     * 获取操作的购物车
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }

        return redisTemplate.boundHashOps(cartKey);
    }
}
